# 学生管理系统
import os.path
import sys

students = []
def save():
    """
    存储数据
    :return:
    """
    with open("record.txt","w",encoding="UTF-8") as f:
        for s in students:
            f.write(f"{s['studentId']}\t{s['studentName']}\t{s['sex']}\t{s['className']}\n")
        print(f"保存了{len(students)}条信息")
def load():
    """
    读档
    :return:
    """
    if not os.path.exists("record.txt"):
        return
    global students
    students = []
    with open("record.txt","r",encoding="UTF-8") as f:
        for line in f:
            line = line.strip()
            tokens = line.split("\t")
            if len(tokens)!=4:
                print(f"当前行格式存在问题 line = {line}")
                continue
            student = {
                "studentId":tokens[0],
                "studentName":tokens[1],
                "sex":tokens[2],
                "className":tokens[3]
            }
            students.append(student)
        print(f"读档成功,共读取到{len(students)}条数据")
def menu():
    print("1.新增学生")
    print("2.显示学生")
    print("3.查找学生")
    print("4.删除学生")
    print("0.退出")
    choice = input("请输入您的选择:")
    return choice
def insert():
    print("{新增学生}开始")
    studentId = input("请输入学生的学号:")
    studentName = input("请输入学生的名字:")
    sex = input("请输入学生的性别:")
    if sex not in ("男","女"):
        print("新增的内容不符合要求,新增失败")
        return
    className = input("请输入学生的班级:")
    student = {
        "studentId":studentId,
        "studentName":studentName,
        "sex":sex,
        "className":className
    }
    global students
    students.append(student)
    save()
    print("{新增学生}结束")
def show():
    print("[显示学生]开始")
    for s in students:
        print(f"{s['studentId']}\t{s['studentName']}\t{s['className']}")
    print(f"[显示学生]结束 共显示了{len(students)}条数据")

def find():
    print("[查找学生]开始")
    name = input("请输入查找学生的姓名:")
    count = 0
    for s in students:
        if name==s['studentName']:
            print(f"{s['studentId']}\t{s['studentName']}\t{s['className']}")
            count+=1
    print(f"[查找学生]结束 共找到{count}名同学")
def delete():
    print("删除学生开始")
    studentId = input("请输入要删除的学生id:")
    for s in students:
        if studentId==s['studentId']:
            print(f"删除{s['studentName']}")
            students.remove(s)
            save()
    print("删除学生结束")
def main():
    """
    入口函数
    """
    print("=========================")
    print("欢迎来到学生管理系统")
    print("=========================")
    load()
    while True:
        choice = menu()
        if choice=='1':
            insert()
        elif choice=='2':
            show()
        elif choice=='3':
            find()
        elif choice=='4':
            delete()
        elif choice=='0':
            print("Good bye!!!")
            sys.exit(0)
        else:
            print("您的输入有误,请重新输入")
            continue


main()